import React, { useState, useEffect, useRef } from 'react';
import { lazyLoadImage } from '@b-design/scroll';
import './style.scss';

const FrameSequence = ({ frameId, FRAME_URLS }) => {
    return (
        <div className="frames">
            {FRAME_URLS.map((url, index) => (
                <img
                    key={index}
                    className={index === frameId ? 'on' : ''}
                    src={url}
                    alt={`frame-${index}`}
                />
            ))}
        </div>
    );
};

const FrameSequenceRender = ({
    frameLength,
    frameUrl,
    frameSuffix = 'jpg',
    hoverStartFrame = 0,
    children,
}) => {
    const [frameId, setFrameId] = useState(hoverStartFrame);
    const [isHovered, setIsHovered] = useState(false);
    const [targetFrame, setTargetFrame] = useState(hoverStartFrame); // 添加状态来跟踪目标帧
    const animationRef = useRef(null);
    const FRAME_URLS = useRef([]);
    const currentFrameRef = useRef(hoverStartFrame);

    // 生成帧URL数组
    useEffect(() => {
        const urls = [];
        for (let i = 0; i < frameLength; i++) {
            const formattedNumber = i.toString().padStart(5, '0');
            urls.push(`${frameUrl}${formattedNumber}.${frameSuffix}`);
        }
        FRAME_URLS.current = urls;

        if (urls.length > 0) {
            lazyLoadImage({
                urls: urls,
                duration: 1,
            });
        }
    }, [frameLength, frameUrl, frameSuffix]);

    // 处理悬停状态变化
    useEffect(() => {
        const newTargetFrame = isHovered ? frameLength - 1 : hoverStartFrame;
        setTargetFrame(newTargetFrame);
    }, [isHovered, frameLength, hoverStartFrame]);

    // 处理帧动画 - 依赖 targetFrame 状态
    useEffect(() => {
        if (FRAME_URLS.current.length === 0) return;

        const animate = () => {
            if (currentFrameRef.current < targetFrame) {
                currentFrameRef.current = Math.min(
                    currentFrameRef.current + 1,
                    targetFrame,
                    FRAME_URLS.current.length - 1
                );
                setFrameId(currentFrameRef.current);
                animationRef.current = requestAnimationFrame(animate);
            } else if (currentFrameRef.current > targetFrame) {
                currentFrameRef.current = Math.max(
                    currentFrameRef.current - 1,
                    targetFrame,
                    0
                );
                setFrameId(currentFrameRef.current);
                animationRef.current = requestAnimationFrame(animate);
            }
        };

        animationRef.current = requestAnimationFrame(animate);

        return () => {
            if (animationRef.current) {
                cancelAnimationFrame(animationRef.current);
            }
        };
    }, [targetFrame]); // 依赖 targetFrame 状态变化

    const handleMouseEnter = () => {
        setIsHovered(true);
    };

    const handleMouseLeave = () => {
        setIsHovered(false);
    };

    return (
        <div
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
            className="frames-container"
            style={{ position: 'relative', height: '100%' }}
        >
            <FrameSequence frameId={frameId} FRAME_URLS={FRAME_URLS.current} />
            {children && (
                <div
                    style={{
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '100%',
                        height: '100%',
                        pointerEvents: 'none', // 确保不会阻挡鼠标事件
                    }}
                >
                    {children}
                </div>
            )}
        </div>
    );
};

export default FrameSequenceRender;
